//
//  Client_RF225_ForkliftController.swift
//  Wmsmobile
//
//  Created by xuNick on 16/10/9.
//  Copyright © 2016年 www.hd123.com. All rights reserved.
//

import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
  switch (lhs, rhs) {
  case let (l?, r?):
    return l > r
  default:
    return rhs < lhs
  }
}


class Client_RF225_ForkliftController: HDFounctionBaseController , HDBarcodeInputCellInputDelegate , HDKeyboardInputCellDelegate , HDNumberInputCellDelegate , HDFounctionBottomViewDelegate{
    //MARK: - property
    var dataArray = [
    ["区域"],
    ["托盘条码" , "货品代码" , "货品名称" , "规格/箱数"],
    ["建议货位"],
    ["上架货位" , "校验码" , "整件/零散"]
    ]
    lazy fileprivate var bottomView:HDFounctionBottomView = {
        let view = HDFounctionBottomView(array: ["上架", "上架异常"])
        return view
    }()
    override var firstActiveIndexPath: IndexPath?{
        set{
        }
        get{
            return IndexPath(item: 0, section: 0)  //在这里添加需要进入界面就激活的cell的位置
        }
    }
    
    //MARK: - lifeCycle
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.addSubview(self.bottomView)
        self.tableView.contentInset.bottom = bottomView.height
        self.bottomView.delegate = self
    }
    //MARK: - delegate
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.bottomView.y = KscreenHeight - bottomView.height + self.tableView.contentOffset.y
    }
    func clickFounctionBottom(_ position: NSInteger) {
        guard self.getText(0, inSection: 3)?.characters.count > 0 else {
            self.showMessage("请输入货位条码", success: false)
            return
        }
        if position == 0 {
            let cell = self.cellsDict[String(describing: IndexPath(item: 2, section: 3))] as! HDNumberInputCell
            self.finishNumInput(cell)
        }else{ //点击了上架异常
            if self.downloadData["poBinCode"] == self.getText(0, inSection: 3){
                self.getData(["piBinCode" : self.getText(0, inSection: 3)! , "piOperator" : (userInfo?.userName)!], bodyMethod: "putAwayExcept", suffix: "330", success: { (dict) in
                    let newVc:HDFounctionBaseController = self.resetController()
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: UInt64(0.5 * Double(NSEC_PER_SEC))), execute: {
                        newVc.showMessage("上架异常成功", success: true)
                    })
                    }, failed: { (dict) in
                        (self.cellsDict[String(describing: IndexPath(item: 1, section: 3))] as! HDInputViewStateProtocol).state = .disabled
                        (self.cellsDict[String(describing: IndexPath(item: 2, section: 3))] as! HDInputViewStateProtocol).state = .disabled
                        (self.cellsDict[String(describing: IndexPath(item: 0, section: 3))] as! HDInputViewStateProtocol).state = .activated
                        self.setText(0, inSection: 3, text: nil)
                        self.setText(1, inSection: 3, text: nil)
//                        self.setText(2, inSection: 3, text: nil)
                })
            }else{
                self.showMessage("输入货位与建议货位不一致", success: false)
                let cell1 = self.cellsDict[String(describing: IndexPath(item: 1, section: 3))] as! HDInputViewStateProtocol
                cell1.state = .disabled
                let cell2 = self.cellsDict[String(describing: IndexPath(item: 2, section: 3))] as! HDInputViewStateProtocol
                cell2.state = .disabled
                let cell3 = self.cellsDict[String(describing: IndexPath(item: 0, section: 3))] as! HDInputViewStateProtocol
                cell3.state = .activated
                self.setText(0, inSection: 3, text: nil)
                self.setText(1, inSection: 3, text: nil)
//                self.setText(2, inSection: 3, text: nil)
            }
        }
    }
    func finishNumInput(_ cell: HDNumberInputCell) {
        //判断货位条码是否一致
        if self.downloadData["poBinCode"] == self.getText(0, inSection: 3) {
            self.finishPutAway(cell)
        }else{
            self.showAlert("提示", message: "输入的货位条码与建议的货位条码不一致，是否继续？", actionLTitle: "取消", actionRTitle: "继续", clickLeft: {
                self.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 3))
                self.setText(0, inSection: 3, text: nil)
                self.setText(1, inSection: 3, text: nil)
//                self.setText(2, inSection: 3, text: nil)
                }, clickRight: {
                    self.finishPutAway(cell)
            })
        }

    }
    func clicKKeyboardReturn(_ cell: HDKeyboardInputCell) {
        let indexpath = self.tableView.indexPath(for: cell)!
        let celltext = cell.codeInputView.textField.text
        switch (indexpath as NSIndexPath).section * 100 + (indexpath as NSIndexPath).row  {
        case 0:
            if celltext?.characters.count < 1 {
                self.showMessage("请输入区域号", success: false)
                return
            }
            self.getData(["piAreaCode" : self.getText(0, inSection: 0) ?? ""], bodyMethod: "getHiBin", suffix: "330", success: { (dict) in
                self.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 1))
                self.setText(0, inSection: 1, text: dict["poPalletCode"])
                self.setText(0, inSection: 2, text: dict["poBinCode"])
                }, failed: { (dict) in
                    cell.state = .wrong
            })
            break
        case 301:
            self.goNextCell(cell, nextInsexPath: IndexPath(item: 2, section: 3))
        default:
            break
        }

        
        
           }
    func clicKReturn(_ cell: HDBarcodeInputCell) {
        let indexpath = self.tableView.indexPath(for: cell)!
        let celltext = cell.codeInputView.textField.text
        switch (indexpath as NSIndexPath).section * 100 + (indexpath as NSIndexPath).row  {
        case 100:
            if celltext?.characters.count < 1 {
                self.showMessage("请输入托盘条码", success: false)
                return
            }
            self.getData(["piPalletCode" : self.getText(0, inSection: 1) ?? "" , "piOperator" : (userInfo?.userName)! , "piType" : "0"], bodyMethod: "getBin", suffix: "330", success: { (dict) in
                self.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 3))
                self.setText(1, inSection: 1, text: dict["poArticleCode"])
                self.setText(2, inSection: 1, text: dict["poArticleName"])
                self.setText(3, inSection: 1, text: "\(dict["poSpec"] ?? "")/\(dict["poQpc"] ?? "")")
                self.setText(0, inSection: 2, text: dict["poBinCode"])
                let pqcString = dict["poSuggestQpc"]?.components(separatedBy: "+")
                
                self.setText(2, inSection: 3, text: "\(pqcString?.first ?? "")/\(pqcString?.count > 1 ? (pqcString?.last ?? "") : "")")
                }, failed: { (dict) in
                    cell.state = .wrong
            })
            break
        case 300:
            if celltext?.characters.count < 1 {
                self.showMessage("请输入上架货位", success: false)
                return
            }
            self.goNextCell(cell, nextInsexPath: IndexPath(item: 1, section: 3))
           default:
            break
        }
    }
    //MARK: - private
    func finishPutAway(_ cell : HDNumberInputCell){
        self.getData(["piBinCode" : self.getText(0, inSection: 3) ?? "" , "piParityBit" : self.getText(1, inSection: 3) ?? "" , "piPalletCode" : self.getText(0, inSection: 1) ?? "" , "piOperator" : (userInfo?.userName)! , "piType" : "0" , "piQpc" : "\(cell.boxNumberTextField.text ?? "0")+\(cell.bagNumberTextField.text ?? "0")"], bodyMethod: "finishPutAway", suffix: "330", success: { (dict) in
            let newVc:HDFounctionBaseController = self.resetController()
            DispatchQueue.main.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: UInt64(1 * Double(NSEC_PER_SEC))), execute: {
                newVc.showMessage("上架成功", success: true)
            })
            }, failed: { (dict) in
                self.goNextCell(cell, nextInsexPath: IndexPath(item: 0, section: 3))
                self.setText(0, inSection: 3, text: nil)
                self.setText(1, inSection: 3, text: nil)
//                self.setText(2, inSection: 3, text: nil)
        })

    }
    override func isEmpty() -> (Bool) { //判断控制器是否为空，必须要实现
        //        if let cell = cellsDict[String(NSIndexPath(forItem: 0, inSection: 0))] as? HDBarcodeInputCell{
        //            if cell.codeInputView.textField.text?.characters.count > 0 {
        //                return false
        //            }else{
        //                return true
        //            }
        //        }
        return true
    }
    //MARK: - tableviewDatasource
    override func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return dataArray[section].count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            if let cell = cellsDict[String(describing: indexPath)] {
                return cell
            }else{
                let position = (indexPath as NSIndexPath).section * 100 + (indexPath as NSIndexPath).row
                var cell: HDFounctionBaseCell?
                switch position {
                case 100,300:
                    cell = HDBarcodeInputCell()
                    (cell as! HDBarcodeInputCell).InputDelegate = self
                case 0,301:
                    cell = HDKeyboardInputCell()
                    (cell as! HDKeyboardInputCell).InputDelegate = self
                case 302:
                    cell = HDNumberInputCell()
                    (cell as! HDNumberInputCell).precisionBox = 0
                    (cell as! HDNumberInputCell).precisionBag = 2
                    (cell as! HDNumberInputCell).delegate = self
                case 103:
                    cell = HDDoubleProductInfocell()
                    let stringArr = (dataArray[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]).components(separatedBy: "/")
                    cell?.titleView.text = stringArr.first
                    (cell as! HDDoubleProductInfocell).titleViewRight.text = stringArr.last
                     cellsDict.updateValue(cell!, forKey: String(describing: indexPath))
                    return cell!
                default:
                    cell = HDProductInfocell()
                    break
                }
                cell?.titleView.text = dataArray[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
                cellsDict.updateValue(cell!, forKey: String(describing: indexPath))
                return cell!
    }
    }
    //MARK: - tableViewDelegate
   
    
}
